<template>
  <el-dialog
    v-model="dialogVisible"
    title="工作报表详情"
    :width="dialogWidth"
    :before-close="handleBeforeClose"
    destroy-on-close
  >
    <!-- 弹窗内容区 -->
    <div class="work-report-dialog">
      <!-- 日期选择器 -->
      <el-date-picker
        v-model="selectedDate"
        type="date"
        format="YYYY/MM/DD"
        value-format="YYYY/MM/DD"
        placeholder="选择日期"
        class="date-picker"
        @change="loadReportData"
      />

      <!-- 基本信息卡片 -->
      <el-card class="basic-info-card">
        <el-descriptions column="4" border>
          <el-descriptions-item label="姓名">{{ reportData.name }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{ reportData.department }}</el-descriptions-item>
          <el-descriptions-item label="职位">{{ reportData.position }}</el-descriptions-item>
          <el-descriptions-item label="报表日期">{{ selectedDate }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ reportData.submitTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusType">{{ reportData.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核人">{{ reportData.reviewer || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">{{ reportData.reviewTime || '-' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 本日行程表格 -->
      <div class="report-section">
        <h3 class="section-title">本日行程</h3>
        <el-table
          :data="reportData.scheduleList"
          border
          stripe
          class="content-table"
          :header-cell-style="tableHeaderStyle"
        >
          <el-table-column
            label="时间"
            prop="time"
            width="100"
            align="center"
          />
          <el-table-column
            label="行程内容"
            prop="content"
            align="left"
          />
          <el-table-column
            label="完成情况"
            prop="status"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-tag :type="scope.row.status === '已完成' ? 'success' : 'info'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 本日计划表格 -->
      <div class="report-section">
        <h3 class="section-title">本日计划</h3>
        <el-table
          :data="reportData.planList"
          border
          stripe
          class="content-table"
          :header-cell-style="tableHeaderStyle"
        >
          <el-table-column
            label="计划名称"
            prop="name"
            width="160"
            align="center"
          />
          <el-table-column
            label="计划内容"
            prop="content"
            align="left"
          />
          <el-table-column
            label="完成进度"
            prop="progress"
            width="160"
            align="center"
          >
            <template #default="scope">
              <el-progress 
                :percentage="scope.row.progress" 
                stroke-width="6"
                :status="scope.row.progress === 100 ? 'success' : undefined"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 业绩统计表格 -->
      <div class="report-section">
        <h3 class="section-title">业绩统计</h3>
        <el-table
          :data="reportData.performanceList"
          border
          stripe
          class="content-table"
          :header-cell-style="tableHeaderStyle"
        >
          <el-table-column
            label="统计项"
            prop="name"
            width="160"
            align="center"
          />
          <el-table-column
            label="数量"
            prop="count"
            width="100"
            align="center"
          />
          <el-table-column
            label="详情"
            prop="details"
            align="left"
          />
          <el-table-column
            label="同比变化"
            prop="growth"
            width="120"
            align="center"
          >
            <template #default="scope">
              <span :class="scope.row.growth > 0 ? 'growth-up' : 'growth-down'">
                {{ scope.row.growth > 0 ? '+' : '' }}{{ scope.row.growth }}%
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 工作小结 -->
      <div class="report-section">
        <h3 class="section-title">工作小结及其他事项</h3>
        <el-card class="summary-card">
          <div class="summary-content">{{ reportData.summary || '无小结内容' }}</div>
        </el-card>
      </div>
    </div>

    <!-- 弹窗底部按钮 -->
    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
      <el-button type="primary" @click="printReport">
        <el-icon><Printer /></el-icon> 打印
      </el-button>
      <el-button 
        type="success" 
        @click="approveReport" 
        v-if="reportData.status === '待审核'"
      >
        审核通过
      </el-button>
      <el-button 
        type="danger" 
        @click="rejectReport" 
        v-if="reportData.status === '待审核'"
      >
        驳回
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, defineProps, defineEmits, watch } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { Printer } from '@element-plus/icons-vue'

// 定义组件属性
const props = defineProps({
  // 控制弹窗显示/隐藏（Vue3默认v-model属性）
  modelValue: {
    type: Boolean,
    default: false
  },
  // 弹窗宽度
  dialogWidth: {
    type: String,
    default: '900px'
  },
  // 初始报表数据
  initialData: {
    type: Object,
    default: () => ({})
  }
})

// 定义组件事件
const emits = defineEmits(['update:modelValue', 'close', 'approve', 'reject', 'load-data'])

// 内部可见性变量（解决v-model双向绑定问题）
const dialogVisible = ref(props.modelValue)

// 监听外部v-model变化，同步到内部状态
watch(
  () => props.modelValue,
  (newVal) => {
    dialogVisible.value = newVal
  }
)

// 监听内部状态变化，同步到外部v-model
watch(
  () => dialogVisible.value,
  (newVal) => {
    emits('update:modelValue', newVal)
  }
)

// 选中的日期
const selectedDate = ref<string>(formatDate(new Date()))

// 报表数据（合并默认数据与传入的初始数据）
const reportData = reactive({
  name: '张明',
  department: '销售部',
  position: '销售经理',
  submitTime: '2024/07/01 18:30',
  status: '待审核', // 待审核/已通过/已驳回
  reviewer: '',
  reviewTime: '',
  scheduleList: [
    { time: '9:00', content: '参加部门早会，明确今日销售目标', status: '已完成' },
    { time: '10:00', content: '拜访A客户，洽谈新产品合作', status: '已完成' },
    { time: '11:30', content: '与B客户电话沟通合同细节', status: '已完成' },
    { time: '13:30', content: '整理客户资料，更新CRM系统', status: '已完成' },
    { time: '15:00', content: '团队内部培训，产品知识分享', status: '已完成' },
    { time: '16:30', content: '制定明日工作计划', status: '已完成' }
  ],
  planList: [
    { name: '品牌销售计划', content: '完成月度销售目标的80%', progress: 85 },
    { name: '品牌回款计划', content: '回收Q2季度30%的应收账款', progress: 60 }
  ],
  performanceList: [
    { name: '新增客源', count: 8, details: '通过市场活动获取', growth: 15 },
    { name: '新增会员', count: 3, details: 'A客户推荐2人，自然增长1人', growth: 5 },
    { name: '成交情况', count: 2, details: 'B客户年度合同，C客户季度订单', growth: -3 }
  ],
  summary: '今日顺利完成各项工作计划，重点推进了A客户的新产品合作，预计下周可以签订合同。B客户的合同细节已确认，明日安排签约。团队培训效果良好，成员对新产品知识掌握到位。明日重点跟进C客户的续约事宜。',
  ...props.initialData
})

// 状态样式映射
const statusType = computed(() => {
  const map: Record<string, string> = {
    '待审核': 'info',
    '已通过': 'success',
    '已驳回': 'danger'
  }
  return map[reportData.status] || 'info'
})

// 表格头部样式
const tableHeaderStyle = {
  'background-color': '#f5f7fa',
  'font-weight': '500',
  'color': '#4e5969'
}

// 格式化日期为YYYY/MM/DD
function formatDate(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// 加载报表数据
const loadReportData = () => {
  // 触发外部数据加载事件
  emits('load-data', selectedDate.value)
  
  // 模拟加载效果
  ElMessage.info(`正在加载 ${selectedDate.value} 的工作报表`)
  
  // 实际项目中可替换为真实数据请求
  setTimeout(() => {
    ElNotification({
      title: '加载成功',
      message: `已加载 ${selectedDate.value} 的工作报表数据`,
      type: 'success',
      duration: 2000
    })
  }, 800)
}

// 打印报表
const printReport = () => {
  ElMessage.info('正在准备打印...')
  // 实际项目中调用打印API
}

// 审核通过
const approveReport = () => {
  ElMessageBox.confirm(
    '确定要审核通过此工作报表吗？',
    '审核确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    const now = new Date()
    reportData.status = '已通过'
    reportData.reviewer = '李经理'
    reportData.reviewTime = `${formatDate(now)} ${now.toTimeString().slice(0, 5)}`
    ElMessage.success('审核已通过')
    emits('approve', {
      date: selectedDate.value,
      reportId: reportData.id
    })
  })
}

// 驳回报表
const rejectReport = () => {
  ElMessageBox.prompt(
    '请输入驳回原因',
    '驳回确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      inputPlaceholder: '请输入驳回原因'
    }
  ).then(({ value }) => {
    if (!value.trim()) {
      ElMessage.warning('请输入驳回原因')
      return
    }
    const now = new Date()
    reportData.status = '已驳回'
    reportData.reviewer = '李经理'
    reportData.reviewTime = `${formatDate(now)} ${now.toTimeString().slice(0, 5)}`
    ElMessage.success('已成功驳回')
    emits('reject', {
      date: selectedDate.value,
      reportId: reportData.id,
      reason: value
    })
  })
}

// 关闭弹窗
const handleCancel = () => {
  dialogVisible.value = false
  emits('close')
}

// 弹窗关闭前的回调
const handleBeforeClose = (done: () => void) => {
  ElMessageBox.confirm('确定要关闭工作报表吗？')
    .then(() => {
      done()
      dialogVisible.value = false
      emits('close')
    })
    .catch(() => {
      // 取消关闭
    })
}
</script>

<style scoped>
.work-report-dialog {
  padding: 5px 0;
}

/* 日期选择器 */
.date-picker {
  width: 160px;
  margin-bottom: 15px;
}

/* 基本信息卡片 */
.basic-info-card {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}

/* 报表区域通用样式 */
.report-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  color: #1d2129;
  font-weight: 600;
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  width: 4px;
  height: 16px;
  background-color: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

/* 内容表格 */
.content-table {
  width: 100%;
  --el-table-row-hover-bg-color: #f0f7ff;
  font-size: 14px;
}

:deep(.el-table td) {
  padding: 10px 0;
}

/* 业绩统计样式 */
.growth-up {
  color: #f56c6c;
}

.growth-down {
  color: #42b983;
}

/* 工作小结 */
.summary-card {
  border-radius: 4px;
}

.summary-content {
  line-height: 1.8;
  color: #4e5969;
  padding: 10px 0;
  white-space: pre-line;
}

/* 响应式适配 */
@media (max-width: 768px) {
  :deep(.el-descriptions) {
    --el-descriptions-column: 2 !important;
  }
  
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 10px auto !important;
  }
}
</style>